cmake_minimum_required(VERSION 3.10)

find_package(BISON REQUIRED)
find_package(FLEX REQUIRED)

set(Target qbc)
configure_file(config.h.in ${CMAKE_BINARY_DIR}/config.h)

if(USE_BISON)
    BISON_TARGET(QBParse parser.ypp  ${CMAKE_BINARY_DIR}/parser.cpp)
    FLEX_TARGET(QBLex qblex.ll  ${CMAKE_BINARY_DIR}/qblex.cpp)
    ADD_FLEX_BISON_DEPENDENCY(QBLex QBParse)
else()
    SET(BISON_QBParse_OUTPUTS parser.cpp)
	SET(FLEX_QBLex_OUTPUTS qblex.cpp)
	message(AUTHOR_WARNING "set -DUSE_BISON=1 on cmake command line if you want to build parser from bison rules")
endif(USE_BISON)

include_directories(${CMAKE_BINARY_DIR})
include_directories(${CMAKE_CURRENT_SOURCE_DIR})

aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR} Sources)


IF (CMAKE_SYSTEM_NAME MATCHES "Linux")
    llvm_map_components_to_libnames(llvm_libs 
        support core Passes Object ObjCARCOpts target
        x86codegen X86AsmParser
        armcodegen ARMAsmParser
        AArch64CodeGen AArch64AsmParser
        AMDGPUCodeGen AMDGPUAsmParser
        BPFCodeGen BPFAsmParser
        HexagonCodeGen 
        MipsCodeGen MipsAsmParser
        LanaiCodeGen
        PowerPCCodeGen PowerPCAsmParser
        MSP430CodeGen
        SparcCodeGen SparcAsmParser
        XCoreCodeGen
        SystemZCodeGen SystemZAsmParser
        NVPTXCodeGen)
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "Windows")
    llvm_map_components_to_libnames(llvm_libs 
        support core Passes Object ObjCARCOpts target
        x86codegen X86AsmParser
        armcodegen ARMAsmParser
        NVPTXCodeGen)
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
    llvm_map_components_to_libnames(llvm_libs all)
ELSE ()
    llvm_map_components_to_libnames(llvm_libs all)
ENDIF (CMAKE_SYSTEM_NAME MATCHES "Linux")


# Link against LLVM libraries
message(STATUS "Using LLVM libs: ${llvm_libs}")

SET(CMAKE_CXX_FLAGS " ${CMAKE_CXX_FLAGS} ${LLVM_CPPFLAGS} ")

add_executable(
    ${Target}
    ${BISON_QBParse_OUTPUTS}
    ${FLEX_QBLex_OUTPUTS}
    ${Sources}
)

target_include_directories(${Target} PRIVATE ${LLVM_INCLUDE_DIRS})
target_compile_definitions(${Target} PRIVATE ${LLVM_DEFINITIONS})
target_link_libraries(${Target} ${llvm_libs} stdc++fs)